package com.itheima.controller;

import com.itheima.entity.Result;
import com.itheima.utlis.AliOSSProperties;
import com.itheima.utlis.AliyunOSSUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

@Slf4j
@RestController
public class UploadController {

//    //文件上传本地存储
//    @PostMapping("/upload")
//    public Result upload(String username, Integer age, MultipartFile  file) throws IOException {
//        log.info("参数：{},{},{}",username,age,file);
//        //获取上传的文件名
//        String originalFilename = file.getOriginalFilename();  //eg 001.002.jpg
//
////        通过uuid生成随机字符串
//        String newFileName = UUID.randomUUID().toString()+originalFilename.substring(originalFilename.lastIndexOf("."));
//
//        //        将前端上传的文件存在本地
//        file.transferTo(new File("D:/"+newFileName));
//        return Result.success(newFileName);
//    }


//    private final String bucketName="java-naiyu";
//    private final String endpoint="https://oss-cn-shenzhen.aliyuncs.com";

//    @Value("${aliyun.oss.bucketName}")
//    private  String bucketName;
//    @Value("${aliyun.oss.endpoint}")
//    private  String endpoint;·
    @Autowired
    private AliOSSProperties aliOSSProperties;

    //文件上传阿里云存储
    @PostMapping("/upload")
    public Result upload(MultipartFile  file) throws Exception {


        //1.获取原始文件名获取后缀
        String originalFilename = file.getOriginalFilename();
        log.info("参数：{}",originalFilename);
        String extName = originalFilename.substring(originalFilename.lastIndexOf("."));  //获取后缀

        //2.调用oss工具类上传文件
        String url = AliyunOSSUtils.upload(aliOSSProperties.getEndpoint(), aliOSSProperties.getBucketName(), file.getBytes(), extName);//getBytes()转为数组

        //返回图片路径
        return Result.success(url);
    }
}
